<?php

namespace app\service;

use app\service\cache\DeviceGroupTableCacheService;
use app\exception\ErrnoPlus;
use app\model\ShareRuleCacheModel;
use app\model\UserDeviceShareModel;
use app\service\cache\UserDeviceShareByAdminCacheService;
use app\service\cache\UserDeviceShareCacheService;
use share\exception\ApiException;
use share\exception\Errno;
use share\service\AmqpService;
use share\service\BaseModelService;
use share\service\MQService;
use share\service\NotifyDingTalkService;
use share\service\UserBaseService;
use share\service\UserDetailService;
use share\utils\Helper;
use think\Log;

class UserDeviceShareService extends BaseModelService
{

    /**
     * 一个设备的最大分享人数
     */
    const DEVICE_MAX_SHARE_TIMES = 32;

    /**
     * 分享规则的默认过期时间
     */
    const SHARE_RULE_EXPIRE = 1800;

    public static function getModel()
    {
        return new UserDeviceShareModel;
    }

    public static function getAllByUser($uid,$filter = [])
    {
        $filter['admin_uid'] = $uid;
        return  UserDeviceShareByAdminCacheService::getAllByFilter($filter);
    }

    public static function getAllByShareUser($uid)
    {
        return UserDeviceShareCacheService::getAllByFilter(['share_uid' => $uid]);
    }

    public static function getAllByMainId($mainIds)
    {
        $mainIds = Helper::arraySmartUnique($mainIds);
        if (count($mainIds) < 1) {
            return [];
        }
        return self::getAllByFilter(['main_id' => ['in',$mainIds]]);
        
    }

    public static function deleteByUser($uid)
    {
        return self::delByFilter(['admin_uid' => $uid]);
    }

    public static function deleteByUserIot($uid, $iotId)
    {
        $filter = [
            'admin_uid' => $uid,
        ];
        if(is_array($iotId)){
            $filter['iot_id'] = ['in',$iotId];
        }
        else{
            $filter['iot_id'] = $iotId;
        }
        return self::delByFilter($filter);
    }

    public static function deleteByShareUser($shareUid)
    {
        return self::delByFilter(['share_uid' => $shareUid]);
    }

    public static function delByFilter($filter)
    {
        if (empty($filter)) {
            NotifyDingTalkService::pushTextByAMQP("删除用户分享时.信息缺失,已取消删除操作");
            try {
                throw new ApiException("deleteByEmptyFilter");
            } catch (\Throwable $th) {
                trace("deleteByEmptyFilter " . json_encode($th->getTrace(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), Log::ERROR);
            }
            return;
        }
        
        //trace("userShareDelete: ".json_encode(debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT,20)),Log::ERROR);

        AmqpService::simplePush([
            'service' => 'app\\service\\UserDeviceShareService@doRealDestoryAsync',
            'params' => $filter,
        ]);

        // MQService::push([
        //     'service' => 'app\\service\\UserDeviceShareService@doRealDestoryAsync',
        //     'params' => $filter,
        // ], MQService::CHANNEL_OF_ACCOUNT);
    }

    public static function doRealDestoryAsync($filter)
    {
        trace("doRealDestoryAsync ".json_encode($filter),Log::ERROR);

        if (empty($filter)) {
            NotifyDingTalkService::pushTextByAMQP("删除用户分享时.信息缺失,已取消删除操作");
            throw new ApiException("can not delete data  because the filter is empty", Errno::COMMON_SYSTEM_ERROR);
        }
        $datas = self::getAllByFilter($filter);
        if ($datas) {
            $model = static::getModel();
            $model::destroy($filter);
            // 要删除的缓存信息
            $admidUids = Helper::arraySmartUnique(array_column($datas, 'admin_uid'));
            $shareIds = Helper::arraySmartUnique(array_column($datas, 'share_uid'));
            $mainIds = Helper::arraySmartUnique(array_column($datas, 'main_id'));

            // 删除自定义分组信息
            foreach ($datas as $data) {
                VirtualDeviceService::delMainDevice($data['main_id'], $data['share_uid']);
            }
            foreach ($shareIds as $shareId) {
                UserDeviceShareCacheService::del(['share_uid' => $shareId]);
            }
            foreach ($admidUids as $admidUid) {
                UserDeviceShareByAdminCacheService::del(['admin_uid' => $admidUid]);
            }
        }
    }

    public static function getRuleCacheByKey($ruleCacheKey)
    {
        $data = ShareRuleCacheModel::get(['cache_key' => $ruleCacheKey]);
        return ShareRuleCacheModel::formatModelData($data);
    }

    public static function addRuleCache($item)
    {
        $tn = time();
        if (!isset($item['create_time'])) {
            $item['create_time'] = $tn;
        };
        if (!isset($item['update_time'])) {
            $item['update_time'] = $tn;
        };
        return ShareRuleCacheModel::create($item);
    }

    public static function updateRuleCache($id, $item)
    {
        $tn = time();
        if (!isset($item['update_time'])) {
            $item['update_time'] = $tn;
        };
        return ShareRuleCacheModel::update($item, [
            'id' => $id,
        ]);
    }

    /**
     * 获取主用户分享设备的信息
     */
    public static function getAllUserShareInfo($shareUid, $iotIds)
    {
        if (!is_array($iotIds)) {
            $iotIds = [$iotIds];
        }
        $data = UserDeviceShareByAdminCacheService::getAllByFilter(['main_id' => ['in', $iotIds], 'admin_uid' => $shareUid]);
        return $data;
    }


    /**
     * 获取分享测试
     */
    public static function countDistinctShareId($filter)
    {
        if (empty($filter)) {
            return 0;
        }
        return UserDeviceShareModel::where($filter)->count('DISTINCT share_uid');
    }

    /**
     * 管理员(主要绑定者)上传分享
     */
    public static function addByAdmin($param, $vendor, $uid)
    {
        $ruleCacheKey = $param['qrcode'];
        $userIdentity = $param['userIdentity'];
        $data = [
            'userIdentity' => $userIdentity,
            'qrcode' => $ruleCacheKey,
            'info' => $param['info'],
            'serverSite' => empty($param['serverSite']) ? "CN" :  $param['serverSite'],
            'admin_uid' => $uid,
        ];

        $ruleCache = self::getRuleCacheByKey($ruleCacheKey);
        $tn = time();
        if (empty($ruleCache)) {
            $cacheData = [
                "cache_key" => $ruleCacheKey,
                "share_rule" => json_encode($data),
                "expired" =>  $tn + self::SHARE_RULE_EXPIRE
            ];
            self::addRuleCache($cacheData);
        } else {
            $updateItem = [
                "share_rule" => json_encode($data),
                "expired" =>  $tn + self::SHARE_RULE_EXPIRE
            ];
            self::updateRuleCache($ruleCache['id'], $updateItem);
        }

        $mqParam = [
            'uid' => $uid,
            'vendor' =>  $vendor,
        ];

        AmqpService::simplePush([
            'service' => 'app\\service\\AliyunProxyService@asyncUserBindInfo',
            'params' => $mqParam,
        ]);

        // MQService::push([
        //     'service' => 'app\\service\\AliyunProxyService@asyncUserBindInfo',
        //     'params' => $mqParam,
        // ], MQService::CHANNEL_OF_ACCOUNT);
    }

    /**
     * 用户上传分享
     */
    public static function addByUser($param, $vendor, $uid)
    {
        $ruleCacheKey = $param['qrcode'];
        $ruleCache = self::getRuleCacheByKey($ruleCacheKey);
        $tn = time();
        if (empty($ruleCache) || intval($ruleCache['expired']) < $tn) {
            throw new ApiException("this share qrcode is expired", ErrnoPlus::INVALID_QRCODE);
        }
        $ruleInfo = json_decode($ruleCache['share_rule'], true);
        if (empty($ruleInfo)) {
            throw new ApiException("the share rule is wrong", ErrnoPlus::INVALID_QRCODE);
        }

        if(isset($ruleInfo['admin_uid'])){
            $shareAdminId = $ruleInfo['admin_uid'];
        }
        else if(isset($ruleInfo['userId'])){ // 老版本的
            $shareAdminUserId = $ruleInfo['userId'];
            $shareAdminUser = UserBaseService::getBase($shareAdminUserId);
            if (empty($shareAdminUser)) {
                throw new ApiException("admin user lost", ErrnoPlus::INVALID_QRCODE);
            }
            $shareAdminId  = $shareAdminUser['id'];
        }
        else{
            throw new ApiException("this share qrcode into lost. no user_info", ErrnoPlus::INVALID_QRCODE);
        }
      
        if ($shareAdminId == $uid) { //不能分享超管自己的设备
            throw new ApiException("can not share self device", ErrnoPlus::SHARE_EXISTS);
        }

        $ruleItems = $ruleInfo['info'];
        if (count($ruleItems) < 1) {
            throw new ApiException("share device info is empty", ErrnoPlus::COMMON_ERROR);
        }
        // 设备基本信息
        $deviceInfo = DeviceInfoTableService::getAll(array_column($ruleItems, 'deviceName'));

        // 设备绑定情况
        $deviceBindingInfo = UserDeviceBindingService::getAllByIotId(array_column($ruleItems, 'iotId'));
        // 已存在的分享信息
        $sharedInfo = self::getAllUserShareInfo($shareAdminId, array_column($ruleItems, 'iotId'));
        $sharedRule = UserDeviceShareRuleService::getAllByIds(array_column($sharedInfo,'id'));
        $tnMs = Helper::getMSTime();
        $addItems = [];
        $updateItems = [];
        foreach ($ruleItems as $item) {
            $iotId = $item['iotId'];
            $currentDeviceInfo = [
                "device_name" => $item["deviceName"],
                "iot_id" => $iotId,
                "ch_num" => intval($item["chNum"]),
                "server_site" => $ruleInfo["serverSite"],
                "vendor" => $vendor,
            ];
            DeviceInfoTableService::compareAndUpsert($currentDeviceInfo, $deviceInfo);

            $deviceBinding = Helper::filterOne($deviceBindingInfo, ['iot_id' => $iotId]);
            if (empty($deviceBinding)) { //设备尚未绑定
                throw new ApiException($iotId . " device is not binding", ErrnoPlus::DEVICE_NOT_BINDING);
            }
            $currentShareInfos = Helper::filter($sharedInfo, ['main_id' => $iotId]);
            $userShareInfo = Helper::filterOne($currentShareInfos, ['share_uid' => $uid]);
            if (empty($userShareInfo)) { //当前用户不在已分享的列表中
                $shareUids = Helper::arraySmartUnique(array_column($currentShareInfos, 'share_uid'));
                //分享次数超限
                if (count($shareUids) >= self::DEVICE_MAX_SHARE_TIMES) {
                    throw new ApiException($iotId . " shared too many times. max is " . self::DEVICE_MAX_SHARE_TIMES, ErrnoPlus::SHARE_TRANSFINITE);
                }
                $shareItems = [
                    "iot_id" => $iotId,
                    "admin_uid" => $shareAdminId,
                    "share_uid" => $uid,
                    "rule" => $item["rule"],
                    "main_id" => $iotId,
                    "vendor" => $vendor,
                    "amqptime" => $tnMs
                ];
                $addItems[] = $shareItems;
            } else {  //当前用户已经分享过
                $rule =  Helper::filterOne($sharedRule, ['id' => $userShareInfo['id']]);
                if (empty($rule) || $rule['rule'] !== $item['rule']) { //规则有变更
                    $update = [
                        'id' => $userShareInfo['id'],
                        "rule" => $item["rule"],
                        "amqptime" => $tnMs
                    ];
                    $updateItems[] = $update;
                }
            }
        }
        self::addMutilShare($addItems);
        self::updateMutilShare($updateItems);
    }

    /**
     * 获取分享的设备信息
     */
    public static function getShareRule($uid, $identityId, $filter = [])
    {
        $selfShare = self::getAllByUser($uid);
        $userShare = self::getAllByShareUser($uid);
        if (empty($selfShare)) {
            $selfShare = [];
        }
        if (empty($userShare)) {
            $userShare = [];
        }
        $userInfo = UserBaseService::getBase($uid);
        $allShare = array_merge($selfShare, $userShare);
        if (empty($allShare)) {
            return [];
        }
        $allShare = Helper::sort($allShare, ['id', 'DESC']);

        $uids = array_merge(array_column($allShare, 'admin_uid'), array_column($allShare, 'share_uid'));
        $ruleInfos = UserDeviceShareRuleService::getAllByIds(array_column($allShare, 'id'));
        $uids = Helper::arraySmartUnique($uids);
        $allUser = UserBaseService::getAll($uids);
        $allUserDetail = UserDetailService::getAll($uids);
        $iotIds = Helper::arraySmartUnique(array_column($allShare, 'main_id'));
        $deviceInfo = DeviceInfoTableService::getAllByIotIds($iotIds);
        $result  = [];

        foreach ($allShare as $share) {
            $shareUser =  Helper::filterOne($allUser, ['id' => $share['share_uid']]);
            $adminUser =  Helper::filterOne($allUser, ['id' => $share['admin_uid']]);

            //构造数据以便 filterShare
            $share['share_id'] = $shareUser ? $shareUser['user_id'] : '';
            $share['user_id'] = $adminUser ? $adminUser['user_id'] : '';

            // 存在筛选条件时
            if (!empty($filter)) {
                if (!self::filterShare($share, $filter)) {
                    continue;
                }
            }
            $device = Helper::filterOne($deviceInfo, ['iot_id' => $share['main_id']]);
            $rule = Helper::filterOne($ruleInfos, ['id' => $share['id']]);
            $base = [
                "rule" => $rule['rule'],
                "mainId" => $share['main_id'],
                "iotId" => $share['iot_id'],
                "deviceName" => empty($device) ? '' : $device['device_name'],
            ];
           
            $shareUserDetail = Helper::filterOne($allUserDetail, ['id' => $share['share_uid']]);
            $adminUserDetail = Helper::filterOne($allUserDetail, ['id' => $share['admin_uid']]);
            if ($share['admin_uid'] == $uid) { // 为自己的设备时
                if (empty($shareUser)) {
                    trace("device share user not found share_id " . $share['share_id'], Log::ERROR);
                    $tmpUser = [
                        "userId" => $userInfo['user_id'],
                        "userIdentity" => $identityId,
                        "shareId" => '',
                        "shareIdentity" => '',
                        "nickName" => '',
                        "pictureUrl" => '',
                    ];
                } else {
                    $tmpUser = [
                        "userId" => $userInfo['user_id'],
                        "userIdentity" => $identityId,
                        "shareId" => $shareUser['user_id'],
                        "shareIdentity" => $shareUser['identity_id'],
                        "nickName" => $shareUserDetail['nick_name'],
                        "pictureUrl" => $shareUserDetail['picture'],
                    ];
                }
            } else {
                if (empty($adminUser)) {
                    trace("device main user not found user_id " . $share['user_id'], Log::ERROR);
                    $tmpUser = [
                        "userId" => '',
                        "userIdentity" => '',
                        "shareId" => $userInfo['user_id'],
                        "shareIdentity" => $identityId,
                        "nickName" => '',
                        "pictureUrl" => '',
                    ];
                } else {
                    $tmpUser = [
                        "userId" => $adminUser["user_id"],
                        "userIdentity" => $adminUser["identity_id"],
                        "shareId" => $userInfo['user_id'],
                        "shareIdentity" => $identityId,
                        "nickName" => $adminUserDetail['nick_name'],
                        "pictureUrl" => $adminUserDetail['picture'],
                    ];
                }
            }
            $result[] = array_merge($base, $tmpUser);
        }
        return $result;
    }

    /**
     * 修改分享规则
     */
    public static function changeShareRule($ruleInfo, $uid)
    {
        $updateInfo = [];
        $iotIds = Helper::arraySmartUnique(array_column($ruleInfo, "iotId"));
        $existShareInfo = self::getAllByFilter([
            'iot_id' => ['in', $iotIds],
            'admin_uid' => $uid,
        ]);
        $shareUids = Helper::arraySmartUnique(array_column($existShareInfo, "share_uid"));
        $shareUsers = UserBaseService::getAll($shareUids);

        foreach ($ruleInfo as $ruleItem) {
            $ruleStr = $ruleItem['rule'];
            $iotId = $ruleItem['iotId'];
            $shareId = $ruleItem['shareId'];
            $shareUser = Helper::filterOne($shareUsers, ['user_id' => $shareId]);
            if (empty($shareUser)) {
                trace("sahreUser not exist when changeShareRule . rule" . json_encode($ruleInfo), Log::ERROR);
                continue;
            }
            $shareInfo = Helper::filterOne($existShareInfo, ['iot_id' => $iotId, 'share_uid' => $shareUser['id']]);
            if (empty($shareInfo)) {
                trace("sahreInfo not exist when changeShareRule . rule" . json_encode($ruleInfo), Log::ERROR);
                continue;
            }
            $newRule = @json_decode($ruleStr, true); // 简单检测 rule 是否为合适的JSON对象
            if ($newRule === null) {
                trace("sahreInfo not exist when changeShareRule . rule" . json_encode($ruleInfo), Log::ERROR);
                continue;
            } else { // 修改分享规则                
                $updateInfo[] = [
                    'id' => $shareInfo['id'],
                    'rule' => $ruleStr,
                ];
            }
        }

        // 更新绑定信息
        foreach ($updateInfo as $item) {
            UserDeviceShareRuleService::update($item['id'], [
                'rule' => $item['rule'],
            ]); 
        }
    }

    /**
     * 删除自身所有的分享
     */
    public static function delAllShare($userId)
    {
        self::deleteByUser($userId);
    }

    /**
     * 通过设备信息等 删除分享
     */
    public static function deleteAllShareByDevice($param)
    {
        foreach ($param as $filter) {
            $shareDelete = [];
            $groupDelete = [];
            if (isset($filter['uid']) && !empty($filter['uid'])) {
                $shareDelete['share_uid'] = $filter['uid'];
                $groupDelete['uid'] = $filter['uid'];
            }
            if (isset($filter['shareId']) && !empty($filter['shareId'])) {
                $userBase = UserBaseService::getByUserId($filter['shareId']);
                if($userBase){
                    $shareDelete['share_uid'] = $userBase['id'];
                    $groupDelete['uid'] = $userBase['id'];
                }
            }
            if (isset($filter['mainId']) && !empty($filter['mainId'])) {
                $shareDelete['main_id'] = $filter['mainId'];
                $groupDelete['main_id'] = $filter['mainId'];
            }
            if (isset($filter['iotId']) && !empty($filter['iotId'])) {
                $shareDelete['iot_id'] = $filter['iotId'];
                $groupDelete['sub_id'] = $filter['iotId'];
            }
            if (count($shareDelete) > 0) {
                self::delByFilter($shareDelete);
            }
            if (isset($groupDelete['main_id']) && isset($groupDelete['uid'])) {
                DeviceGroupTableService::delByFilter($groupDelete);
            }
        }
        //删除缓存
        DeviceGroupTableCacheService::delAllByUserIds(array_column($param, 'shareId'));
    }

    /**
     * 获取分享次数信息
     */
    public static function getShareCountInfo($param, $uid, $vendor)
    {
        $mainId = $param['mainId'];
        $deviceInfo = DeviceInfoTableService::getByIotId($mainId);
        if (empty($deviceInfo)) {
            AmqpService::simplePush([
                'service' => 'app\\service\\AliyunProxyService@asyncUserBindInfo',
                'params' => [
                    'uid' => $uid,
                    'vendor' => $vendor,
                ],
            ]);

            // MQService::push([
            //     'service' => 'app\\service\\AliyunProxyService@asyncUserBindInfo',
            //     'params' => [
            //         'uid' => $uid,
            //         'vendor' => $vendor,
            //     ],
            // ], MQService::CHANNEL_OF_ACCOUNT);
        }
        $bindDevice = UserDeviceBindingService::getAllByUser($uid, ['iot_id' => $mainId]);
        if (empty($bindDevice)) {
            $mqParam = [
                "iotId" => $mainId,
                "vendor" => $vendor,
            ];
            AmqpService::simplePush([
                'service' => 'app\\service\\AliyunProxyService@asyncDeviceBindInfoByIotId',
                'params' =>  $mqParam,
            ]);

            // MQService::push([
            //     'service' => 'app\\service\\AliyunProxyService@asyncDeviceBindInfoByIotId',
            //     'params' =>  $mqParam,
            // ], MQService::CHANNEL_OF_ACCOUNT);


            throw new ApiException("the device is not binding", ErrnoPlus::DEVICE_NOT_BINDING);
        }
        $count = self::countDistinctShareId([
            "admin_uid" => $uid,
            "main_id" => $mainId
        ]);
        if ($count === false) {
            $count = 0;
        }
        $extendNum = empty($deviceInfo) ? 0 : $deviceInfo['extend_num'];
        $res = [
            "count" => $extendNum + self::DEVICE_MAX_SHARE_TIMES - $count,
            "total" => $extendNum + self::DEVICE_MAX_SHARE_TIMES
        ];
        return $res;
    }

    /**
     * 主动分享
     */
    public static function toShare($param, $adminId, $vendor)
    {
        $shareItemInfo = $param['info'];
        $userIds = array_column($shareItemInfo, 'shareId');
        $iotIds = array_column($shareItemInfo, 'mainId');
        $allShareUser = UserBaseService::getAllByUserId($userIds);
        $devices = DeviceInfoTableService::getAllByIotIds($iotIds);
        $bindDevices = UserDeviceBindingService::getAllByUser($adminId);
        $sharedDevices = self::getAllByUser($adminId);

        $tnMs = Helper::getMSTime();

        // 前置的用户判断 
        foreach ($shareItemInfo as $item) {
            $userId = $item['shareId'];
            $userIdentity = $item['shareIdentity'];
            $shareUserInfo = Helper::filterOne($allShareUser, ['user_id' => $userId]);
            if (empty($shareUserInfo)) {
                throw new ApiException("user " . $userId . " not exists", ErrnoPlus::COMMON_ERROR);
            }
            if ($shareUserInfo['identity_id'] !== $userIdentity) {
                throw new ApiException("userIdentity is wrong", ErrnoPlus::COMMON_ERROR);
            }
        }
        $addItems = [];
        $updateItems = [];
        foreach ($shareItemInfo as $item) {
            $tmpDevice = [
                'device_name' => $item['deviceName'],
                "iot_id" => $item["iotId"],
                "ch_num" => $item["chNum"],
                "server_site" => $item["serverSite"],
                "vendor" => $vendor,
            ];
            DeviceInfoTableService::compareAndUpsert($tmpDevice, $devices);
            $bindInfo = Helper::filterOne($bindDevices, ['iot_id' => $item['mainId']]);
            if (empty($bindInfo)) { // 不存在绑定信息 直接返回                
                $mqParam = [
                    'iotId' => $item['iotId'],
                    'vendor' => $vendor,
                ];

                AmqpService::simplePush([
                    'service' => 'app\\service\\AliyunProxyService@asyncDeviceBindInfoByIotId',
                    'params' => $mqParam,
                ]);

                // MQService::push([
                //     'service' => 'app\\service\\AliyunProxyService@asyncDeviceBindInfoByIotId',
                //     'params' => $mqParam,
                // ], MQService::CHANNEL_OF_ACCOUNT);

                throw new ApiException("mainId " . $item['mainId'] . " not found bind info", ErrnoPlus::COMMON_ERROR);
            } else {
                if ($bindInfo['iot_id'] !== $item['iotId'] || $bindInfo['vendor'] !== $vendor || $bindInfo['uid'] !== $adminId) {
                    $update = [
                        'iot_id' => $item['iotId'],
                        'vendor' => $vendor,
                        'uid' => $adminId,
                        'amqptime' => $tnMs,
                    ];
                    UserDeviceBindingService::update($bindInfo['id'], $update);
                }
            }
            $currentShareUserInfo = Helper::filterOne($allShareUser, ['user_id' => $item['shareId']]);

            $tmpShare = Helper::filterOne($sharedDevices, ['iot_id' => $item['iotId'], 'share_uid' => $currentShareUserInfo['id']]);
            if (empty($tmpShare)) { // 不存在分享时 创建一条分享
                $tmpShareData = [
                    "iot_id" => $item["iotId"],
                    "admin_uid" => $adminId,
                    "share_uid" => $currentShareUserInfo["id"],
                    "rule" => $item["rule"],
                    "main_id" => $item["mainId"],
                    "vendor" => $vendor,
                    "amqptime" => $tnMs,
                ];
                $addItems[] = $tmpShareData;
            } else {
                // 数据变更时 更新
                if ($tmpShare['rule'] !== $item['rule'] || $tmpShare['vendor'] !== $vendor || $tmpShare['main_id'] !== $item['mainId']) {
                    $update = [
                        'amqptime' => $tnMs,
                    ];
                    if ($tmpShare['rule'] !== $item['rule']) {
                        $update['rule'] = $item['rule'];
                    }
                    if ($tmpShare['vendor'] !== $vendor) {
                        $update['vendor'] = $vendor;
                    }
                    if ($tmpShare['main_id'] !== $item['mainId']) {
                        $update['main_id'] = $item['mainId'];
                    }
                    $update['id'] = $tmpShare['id'];
                    $updateItems[] = $update;                 
                }
            }
        }

        self::addMutilShare($addItems);
        self::updateMutilShare($updateItems);
    }



    /**
     * 某条分享记录的详情
     */
    public static function shareDetailInfo($id)
    {
        $share = self::getBase($id);
        if (empty($share)) {
            throw new ApiException("share info is not exist", ErrnoPlus::COMMON_ERROR);
        }
        $rule = UserDeviceShareRuleService::getBase($id);
        $device = DeviceInfoTableService::getByIotId($share['iot_id']);
        $bindUser = UserBaseService::getBase($share['admin_uid']);
        $bindUserDetail = UserDetailService::getBase($share['admin_uid']);
        $shareUser = UserBaseService::getBase($share['share_uid']);
        return [
            'bindingEmail' => isset($bindUser['email']) ? $bindUser['email'] :  '',
            'bindingId' => isset($bindUser['user_id']) ? $bindUser['user_id'] :  '',
            'bindingIdentity' => isset($bindUser['identity_id']) ? $bindUser['identity_id'] :  '',
            'bindingPhone' => isset($bindUser['phone']) ? $bindUser['phone'] :  '',
            'serverSite' => isset($bindUserDetail['server_site']) ? $bindUserDetail['server_site'] :  '',
            'shareEmail' => isset($shareUser['email']) ? $shareUser['email'] :  '',
            'shareId' => isset($shareUser['user_id']) ? $shareUser['user_id'] :  '',
            'shareIdentity' => isset($shareUser['identity_id']) ? $shareUser['identity_id'] :  '',
            'sharePhone' => isset($shareUser['phone']) ? $shareUser['phone'] :  '',
            'chNum' => isset($device['ch_num']) ? $device['ch_num'] :  '',
            'deviceName' => isset($device['device_name']) ? $device['device_name'] :  '',
            'extendNum' => isset($device['extend_num']) ? $device['extend_num'] :  '',
            'iotId' => isset($device['iot_id']) ? $device['iot_id'] :  '',
            'rule' => $rule['rule'],
        ];
    }

    protected static function filterShare($base, $filters)
    {
        if (empty($filters)) {
            return true;
        }
        foreach ($filters as $filter) {
            $test = true;
            foreach ($filter as $key => $val) {
                $underLineKey = Helper::camelToUnderscore($key);
                if ($base[$underLineKey] != $val) {
                    $test = false;
                    break;
                }
            }
            if ($test) {
                return true;
            }
        }
        return false;
    }

    public static function buildCondition($filter)
    {
        $res = [];
        if (isset($filter['userId']) && !empty($filter['userId'])) {
            $user = UserBaseService::getByUserId($filter['userId']);
            if($user){
                $res['admin_uid'] = $user['id'];
            }
        }

        if (isset($filter['mainId']) && !empty($filter['mainId'])) {
            $res['main_id'] = $filter['mainId'];
        }
        return $res;
    }

    /**
     * 批量添加
     */
    protected static function addMutilShare($shareInfos){
        if(empty($shareInfos)){
            return;
        }
        $admidUids = [];
        $uids = [];
        // $mainIds = [];
        foreach($shareInfos as $shareItem){
            $item = $shareItem;
            $rule = isset($item['rule']) ? $item['rule'] : null;
            if($rule){
                unset($item['rule']);
            }
            $uids[] = $item['share_uid'];
            $admidUids[] = $item['admin_uid'];
            $addRes = self::add($item);
            if($addRes && $rule){
                UserDeviceShareRuleService::add([
                    'id' => $addRes['id'],
                    'rule' => $rule,
                ]);
            }
        }
        $uids = Helper::arraySmartUnique($uids);
        foreach($uids as $uid){
            UserDeviceShareCacheService::del(['share_uid' => $uid]);
        }

        $admidUids = Helper::arraySmartUnique($admidUids);
        foreach($admidUids as $admidUid){
            UserDeviceShareByAdminCacheService::del(['admin_uid' => $admidUid]);
        } 
    }

    /**
     * 批量更新
     */
    protected static function updateMutilShare($shareInfos){
        if(empty($shareInfos)){
            return;
        }
        $uids = [];
        $adminUids = [];
        foreach($shareInfos as $shareItem){
          
            $item = $shareItem;
            $id = $item['id'];
            unset($item['id']);            
            $rule = isset($item['rule']) ? $item['rule'] : null;
            if($rule){
                unset($item['rule']);
            }
            if(isset($item['share_uid'])){
                $uids[] = $item['share_uid'];
            }

            if(isset($item['admin_uid'])){
                $adminUids[] = $item['admin_uid'];
            }            
            self::update($id,$item);
            if($rule){
                UserDeviceShareRuleService::update($id,[
                    'rule' => $rule,
                ]);
            }
        }

        $uids = Helper::arraySmartUnique($uids);
        foreach($uids as $uid){
            UserDeviceShareCacheService::del(['share_uid' => $uid]);
        }

        $adminUids = Helper::arraySmartUnique($adminUids);
        foreach($adminUids as $adminUid){
            UserDeviceShareByAdminCacheService::del(['admin_uid' => $adminUid]);
        } 

    }
}
